package com.lagou.guava.service;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lagou.guava.dao.PositionDao;
import com.lagou.guava.model.Position;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PositionServiceImpl
 * @Description TODO
 * @Author xsq
 * @Date 2020/11/4 17:26
 **/
@Service
public class PositionServiceImpl {
    @Autowired
    private PositionDao positionDao;
    @Autowired
    private RedisTemplate redisTemplate;

    LoadingCache<String, List<Position>> cacheLoader = CacheBuilder.newBuilder()
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .build(new CacheLoader<String, List<Position>>() {
                @Override
                public List<Position> load(String s) throws Exception {
                    String jsonString = (String)redisTemplate.opsForValue().get(s);
                    List<Position> data = JSON.parseArray(jsonString, Position.class);
                    if (data != null) {
                        return data;
                    }
                    List<Position> all = positionDao.findAll();
                    if (all != null && !all.isEmpty()) {
                        redisTemplate.opsForValue().set("HOT_KEY", JSON.toJSONString(all));
                        return all;
                    }
                    return null;
                }
            });


    public List<Position> getHotList() throws ExecutionException {
        return cacheLoader.get("HOT_KEY");
    }

}
